package com.fh.reflection;
import com.fh.Cat;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 方小勤
 * @version 1.0~
 */
public class Reflection02 {
    public static void main(String[] args) throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        m1();//传统
        m2();//反射
        m3();//反射优化
    }
    public static void m1(){
        Cat cat = new Cat();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            cat.hi();
        }
        long end = System.currentTimeMillis();
        System.out.println("m1()耗时 = "+(end - start)+"ms");
    }
    public static void m2() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> cls = Class.forName("com.fh.Cat");
        Object o = cls.getDeclaredConstructor().newInstance();
        Method method = cls.getMethod("hi");
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            method.invoke(o);//反射调用方法
        }
        long end = System.currentTimeMillis();
        System.out.println("m2()耗时 = "+(end-start)+"ms");
    }
    public static void m3() throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class<?> cls = Class.forName("com.fh.Cat");
        Object o = cls.getDeclaredConstructor().newInstance();
        Method method = cls.getMethod("hi");
        method.setAccessible(true);//在反射调用方法时，取消访问检查
        long start = System.currentTimeMillis();
        for (int i = 0; i < 900000000; i++) {
            method.invoke(o);//反射调用方法
        }
        long end = System.currentTimeMillis();
        System.out.println("m2()耗时 = "+(end-start)+"ms");
    }
}
